//
//  XOWMWebView.m
//  XOWMSDK
//
//  Created by SKL on 2017/12/5.
//  Copyright © 2017年 SKL. All rights reserved.
//

#import "XOWMWebView.h"
#import <WebKit/WebKit.h>

@interface XOWMWebView()<WKNavigationDelegate>
{
    int _index;
}
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIView *naviLine;
@property (nonatomic, strong) UIView *line;
@property (nonatomic, strong) XOWMCustomButton *button;
@end
@implementation XOWMWebView
- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.naviLine.hidden = NO;
        self.button.hidden = NO;
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (UIView *)naviLine
{
    if (!_naviLine)
    {
        _naviLine = [[UIView alloc]init];
        self.line.hidden = NO;
        [self addSubview:_naviLine];
        _naviLine.c_edges.equal(UIEdgeInsetsMake(0, 0, SCREEN_HEIGHT - 44, 0));
    }
    return _naviLine;
}

- (UIView *)line
{
    if (!_line)
    {
        _line = [[UIView alloc]init];
        _line.backgroundColor = [UIColor lightGrayColor];
        [self.naviLine addSubview:_line];
        _line.c_edges.equal(UIEdgeInsetsMake(43.5, 0, 0, 0));
    }
    return _line;
}
- (XOWMCustomButton *)button
{
    if (!_button)
    {
        _button = [[XOWMCustomButton alloc]initWithBackIMG:@"back"];
        [_button addTarget:self action:@selector(yjd_actionForButtton) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_button];
        _button.c_left.equal(self).with.coffset(5);
        _button.c_top.equal(self);
        _button.c_size.equal(CGSizeMake(44, 44));
    }
    return _button;
}

- (WKWebView *)webView
{
    if (!_webView)
    {
        _webView = [[WKWebView alloc]init];
        _webView.navigationDelegate = self;
        [self addSubview:_webView];
        _webView.c_edges.equal(UIEdgeInsetsMake(44, 0, 0, 0));
    }
    return _webView;
}

- (void)yjd_show:(NSString *)url
{
    [CCHud startHud];
    NSString *new_url  = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:new_url]];
    request.HTTPMethod = @"GET";
    [self.webView loadRequest:request];
}

- (void)yjd_actionForButtton
{
    [CCHud stopHud];
    
    if (self.delegate  && [self.delegate respondsToSelector:@selector(yjd_actionForWebView)])
    {
        [self yjd_cleanCacheAndCookie];
        [self.delegate yjd_actionForWebView];
    }
}

/**清除缓存和cookie*/
- (void)yjd_cleanCacheAndCookie{
    //清除cookies
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]){
        [storage deleteCookie:cookie];
    }
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
}

#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    [CCHud startHud];
    DeLog(@"页面开始加载时调用");
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    DeLog(@"当内容开始返回时调用");
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [CCHud stopHud];
    DeLog(@"页面加载完成之后调用");
    
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    [CCHud stopHud];
    DeLog(@"页面加载失败时调用");
    
}
// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    [CCHud  startHud];
    DeLog(@"接收到服务器跳转请求之后调用");
    
}

// 跳转失败时调用
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    DeLog(@" 跳转失败时调用");
}

//拦截判断
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    DeLog(@"======= url = %@",[navigationAction.request.URL absoluteString]);
    WKNavigationActionPolicy policy = WKNavigationActionPolicyAllow;
    /* 简单判断host，真实App代码中，需要更精确判断itunes链接 */
    if ([[navigationAction.request.URL absoluteString] containsString:@"weixin://"] )
    {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]])
        {
            [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
            //             policy = WKNavigationActionPolicyCancel;
        }
        else
        {
            policy = WKNavigationActionPolicyCancel;
            decisionHandler(policy);
            return    [CCHud stopHud:^{
                [CCAlert showMessage:@"未安装微信,请先安装" title:@"注意" enter:^{
                    [self yjd_actionForButtton];
                }];
            }];
            
        }
    }
    decisionHandler(policy);
    
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */


- (void)sp_getUsersMostLikedSuccess {
    NSLog(@"Get User Succrss");
}
@end
